const config = require("../config")

const uri = config.request.uri
const port = config.request.port
const useCloud = config.request.useCloud

function sendRequest(object){
  return new Promise((resolve,reject) => {
    if(!object || !object.url){
      reject({code:500,msg:'错误参数'})
    }
    let urlP
    let dataP
    let methodP
    //处理请求地址
    urlP = object.url
    //拼接请求地址  --判断端口，如果为80端口则不拼接端口号
    urlP = uri + (port == 80 ? '' : (':' + port)) + ((urlP.substring(0, 1) === "/")?'':'/') + urlP

    //如果没有传请求数据则默认为空对象方便后续代码添加id数据
    dataP = object.data || {}
    //如果没有穿请求方式则默认使用‘get’
    methodP = (object.method || 'GET').toUpperCase()

    //如果是空置的参数则删除不传
    for(let item in dataP){
      if (!(dataP[item] != null && dataP[item] != undefined)) {
        delete dataP[item]
      }
    }

    //使用云函数
    if(useCloud){
      wx.cloud.callFunction({
        name:"sendRequest",
        data:{
          url:urlP,
          data:dataP,
          method: methodP
        },
        success:res => {
          if(res){
            //处理返回的数据(和本地请求统一)
            let backObject = {
              statusCode: res.result.statusCode,
              errMsg: res.errMsg,
              header: res.result.headers,
              data: res.result.body
            }
            if (object.success) {
              object.success(backObject)
            }
            if (object.complete) {
              object.complete(backObject)
            }
            resolve(backObject)
          }else{
            resolve()
          }
          
        },
        fail:res => {
          if (object.fail) {
            object.fail(res)
          }
          if (object.complete) {
            object.complete(res)
          }
          reject(res)
        }
      })

    }else{
      //使用本地请求

      let openid = config.request.openid
      let appid = config.request.appid
      let buffer = config.request.buffer

      let localRequestOPENID = wx.getStorageSync('localRequestOPENID')
      let localRequestAPPID = wx.getStorageSync('localRequestAPPID')

      if (((!openid || !appid) || !buffer) || (buffer && (!localRequestOPENID || !localRequestAPPID))){
        wx.cloud.callFunction({
          name: "login",
          success: res => {
            
            if (res && res.result) {
              wx.setStorageSync('localRequestOPENID',res.result.openid)
              wx.setStorageSync('localRequestAPPID',res.result.appid)
              
              dataP.appid = res.result.appid
              dataP.openid = res.result.openid

              //调用本地请求
              localRequest(urlP, dataP, methodP).then(res => {
                
                if (res && res.statusCode === 200){
                  if (object.success) {
                    object.success(res)
                  }
                  if (object.complete) {
                    object.complete(res)
                  }
                  resolve(res)
                }else{
                  if (object.fail) {
                    object.fail(res)
                  }
                  if (object.complete) {
                    object.complete(res)
                  }
                  reject(res)
                }

              }).catch(res => {
                if (object.fail) {
                  object.fail(res)
                }
                if (object.complete) {
                  object.complete(res)
                }
                reject(res)
              })

            }
            
          },
          fail: res => {
            console.error("login获取用户信息失败",res);
            reject(res)
          }
        })
      }else{
        
        if (openid && appid){
          //如果有进行配置则使用配置的id
          dataP.appid = appid
          dataP.openid = openid
        }else{
          //如果没有配置则使用缓存的id
          dataP.appid = localRequestOPENID
          dataP.openid = localRequestAPPID
        }


        //调用本地请求
        localRequest(urlP, dataP,methodP).then(res => {
          if (object.success) {
            object.success(res)
          }
          if (object.complete) {
            object.complete(res)
          }
          resolve(res)
        }).catch(res => {
          if (object.fail) {
            object.fail(res)
          }
          if (object.complete) {
            object.complete(res)
          }
          reject(res)
        })
      }
    }
  })
}
//处理地址(地址后如果不存在斜杠则补上'/')
function disposeAddess(url){
  return ((url.substring(0, 1) === "/") ? '' : '/') + url
}
//本地请求
function localRequest(urlP, dataP, methodP){
  return new Promise((resolve, reject) => {

    wx.request({
      url: urlP,
      header:{
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      data: dataP,
      method: methodP,
      success: (res) => {
        if (res){
          //处理返回的数据(和云函数统一)
          let backObject = {
            statusCode: res.statusCode,
            errMsg: res.errMsg,
            header: res.header,
            data: res.data
          }
          resolve(backObject);
        }else{
          resolve()
        }
        
      },
      fail: (res) => {
        reject(res)
      }
    })
  })
}

export default sendRequest